package com.example.framework509.common.aspects;

import com.example.framework509.common.entities.ResMsg;
import com.example.framework509.common.exceptions.base.BaseCustomException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
public class HandlerExceptionAspect {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResMsg process(Throwable cause, HttpServletRequest request, HttpServletResponse response) {
        ResMsg resMsg;
        if (cause instanceof BaseCustomException) {
            BaseCustomException baseCustomException = (BaseCustomException) cause;
            resMsg = ResMsg.failResOneMes(baseCustomException.getMessage(), baseCustomException.getCode());
        } else {
            resMsg = ResMsg.failResOneMes(cause.getMessage(), 1101);
        }
        this.setHeader(request, response);
        return resMsg;
    }

    private void setHeader(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
    }
}
